package com.framework.web.sys.controller;


import com.framework.core.constant.Globals;
import com.framework.core.domain.AjaxJson;
import com.framework.core.domain.SessionVo;
import com.framework.core.easyui.domain.DataGridModel;
import com.framework.core.easyui.util.PageUtil;
import com.framework.core.util.ContextHolderUtils;
import com.framework.core.util.MD5Util;
import com.framework.core.util.MyBeanUtils;
import com.framework.web.common.mappings.SysUrlMappings;
import com.framework.web.sys.domain.User;
import com.framework.web.sys.service.RoleService;
import com.framework.web.sys.service.UserRoleService;
import com.framework.web.sys.service.UserService;
import com.framework.web.sys.vo.RoleVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户信息管理——控制层
 *
 * @author fusf
 */
@Controller
public class UserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Spring注入资源信息模块service
     */
    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;


    /**
     * 获取用户信息列表
     *
     * @param dgm
     * @param user
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_USER_LIST, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> list(DataGridModel dgm, User user, HttpServletRequest request) throws Exception {
        PageRequest pr = DataGridModel.getPageRequest(dgm);
        return PageUtil.getPageMap(userService.getPageList(user, pr));
    }

    /**
     * 用户信息模块添加、修改页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_USER_TOSAVEANDUPDATE, method = RequestMethod.GET)
    public ModelAndView toSaveAndUpdate(@PathVariable("id") String id, @PathVariable("orgId") String orgId)
            throws Exception {
        ModelAndView modelAndView = new ModelAndView(SysUrlMappings.V_SYS_USER_TOSAVEUPDATE);
        User user = new User();
        if (StringUtils.isNotEmpty(id) && !"0".equals(id)) {
            user = userService.findById(id);
        } else {
            // 初始化默认状态
            user.setStatus(Globals.USER_NORMAL);
            if (StringUtils.isNotEmpty(orgId) && !"0".equals(orgId)) {
                user.setOrgId(orgId);//机构Id
            }
        }

        modelAndView.addObject("user", user);
        return modelAndView;
    }


    /**
     * 添加或修改用户信息构实体
     *
     * @param user 用户信息实体
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_USER_SAVEANDUPDATE, method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveAndUpdate(HttpServletRequest request, HttpServletResponse response, User user) throws Exception {
        AjaxJson j = new AjaxJson();
        if (StringUtils.isNotEmpty(user.getId())) {//更新
            User r = userService.findById(user.getId());
            MyBeanUtils.copyBeanNotNull2Bean(user, r);
            user = r;
        }else {
            user.setUserPwd(MD5Util.encodeStr(Globals.INIT_PWD));//密码初始化
        }
        if(Globals.USER_FORBIDDEN.equals(user.getStatus())) {//设置离职时间
            user.setStatusDate(new Date());
        }
        userService.save(user);
        j.setMsg("保存成功");
        return j;
    }

    /**
     * 根据id字符串删除指定资源信息数据
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_USER_DELETE, method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(String id) throws Exception {
        AjaxJson j = new AjaxJson();
        userService.delete(id);
        j.setMsg("删除成功");
        return j;
    }


    /**
     * 用户分配角色之前
     *
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_USER_TOALLOCATEROLE, method = RequestMethod.GET)
    public ModelAndView toUpdatePostRole(@PathVariable("id") String id, HttpServletRequest request)
            throws Exception {
        ModelAndView modelAndView = new ModelAndView(SysUrlMappings.V_SYS_USER_TOALLOCATEROLE);
        User user = userService.findById(id);
        List<RoleVo> roleVoList = userRoleService.findCheckRoleByUserId(id);
        modelAndView.addObject("user", user);
        modelAndView.addObject("roleList", roleVoList);
        return modelAndView;
    }

    /**
     * 变更用户角色信息
     *
     * @param request
     * @param response
     * @param id
     * @param roleId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_USER_ROLE_SAVEANDUPDATE, method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveRoleUser(HttpServletRequest request, HttpServletResponse response, String id, String roleId) throws Exception {
        AjaxJson j = new AjaxJson();
        userRoleService.saveUserRole(id,roleId);
        j.setMsg("角色变更成功");
        return j;

    }

    /**
     * 用户修改密码
     *
     * @param oldPwd
     * @param newPwd
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_USERINFO_UPDATE_PWD)
    @ResponseBody
    public Object updatePwd(String oldPwd, String newPwd) throws Exception {
        AjaxJson j = new AjaxJson();
        SessionVo svo = ContextHolderUtils.getSessionVo();
        User user = userService.findById(svo.getUserId());
        if (user != null) {
            if (user.getUserPwd().equals(MD5Util.encodeStr(oldPwd))) {
                user.setUserPwd(MD5Util.encodeStr(newPwd));
                userService.save(user);
                j.setMsg("修改密码成功");
            } else {
                j.setSuccess(false);
                j.setMsg("密码错误");
            }
        } else {
            j.setSuccess(false);
            j.setMsg("用户不存在");
        }
        return j;
    }







}